package com.hfi.security.core.social.qq.connect;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author ChangLiang
 * @date 2019/8/21
 */
public class QQOAuth2Template extends OAuth2Template {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        // useParametersForClientAuthentication=true，其才会带上client_id和client_secret
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        String s = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
        logger.info("获取到qq的accessToken响应:{}", s);
        try {
            String[] strings = StringUtils.splitByWholeSeparatorPreserveAllTokens(s, "&");
            String accessToken = StringUtils.substringAfterLast(strings[0], "=");
            Long expiresIn = Long.valueOf(StringUtils.substringAfterLast(strings[1], "="));
            String refreshToken = StringUtils.substringAfterLast(strings[2], "=");
            return new AccessGrant(accessToken, null, refreshToken, expiresIn);
        } catch (Exception e) {
            throw new RuntimeException("获取qq的access Token响应出错");
        }
    }

    @Override
    protected RestTemplate getRestTemplate() {
        RestTemplate restTemplate = super.getRestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        return restTemplate;
    }
}
